package com.ydd.controller.user;

import com.ydd.result.Result;
import com.ydd.service.IArticleService;
import com.ydd.vo.ArticleShowVO;
import com.ydd.vo.UploadVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.time.LocalDate;
import java.util.UUID;

/**
 * @Description TODO
 * @Author itbobo
 * @Date 2023-06-02 16:20
 */
@Api(tags = "文件上传相关接口")
@Slf4j
@RestController
public class UploadController {

    @Value("${ydd.fileUpload.backend-nginx-path}")
    private String backendNginxPath;
    @Value("${ydd.fileUpload.front-nginx-path}")
    private String frontNginxPath;

    @Autowired
    private IArticleService articleService;

    /**
     * 文章详情数据接口
     * @param id
     * @return
     */
    @ApiOperation("文章详情数据接口")
    @GetMapping("/index/show")
    public Result<ArticleShowVO> show(Integer id){
        //打印日志信息
        log.info("文章详情数据:{}", id);
        //调用业务层方法
        ArticleShowVO articleShowVO = articleService.show(id);
        //返回数据
        return Result.success(articleShowVO);
    }

    /**
     * 后台文件上传
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/admin/common/upload")
    public Result adminUpload(MultipartFile file) throws Exception {
        UploadVO uploadVO = getUploadVO(file,1);
        return Result.success(uploadVO);
    }

    /**
     * 前台文件上传
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/api/common/upload")
    public Result apiUpload(MultipartFile file) throws Exception {
        //1、创建文件名
        UploadVO uploadVO = getUploadVO(file,2);
        return Result.success(uploadVO);
    }


    /**
     * 文件上传既要保存到前台nginx又要保存到后台nginx
     * @param file
     * @param type 1,是后台请求；2，是前台请求
     * @return
     * @throws IOException
     */
    private UploadVO getUploadVO(MultipartFile file ,Integer type) throws IOException {
        //1、创建文件名
        String originalFilename = file.getOriginalFilename();
        String jpg = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString().replace("-", "") + jpg;

        //当天日期
        String today = LocalDate.now().toString().replace("-", "");
        //前端访问路径：undefinedupload/images/图片名
        String backendRelativePath = "upload/images/" + today + "/";

        //后台nginxPath是nginx的地址
        String backendPath = backendNginxPath + "\\html\\dist\\undefinedupload\\images\\" + today + "\\";
        //创建后台目录
        File saveBackendPath = new File(backendPath);
        if (!saveBackendPath.exists()) {
            saveBackendPath.mkdirs();
        }
        //上传到后台文件
        file.transferTo(new File(backendPath + fileName));

        //前端访问路径：apiupload/images/图片名
        String frontRelativePath = "upload/images/" + today + "/";
        //前台nginxPath是nginx地址
        String frontPath = frontNginxPath + "\\html\\dist\\apiupload\\images\\" + today + "\\";
        //创建前台目录
        File saveFrontPath = new File(frontPath);
        if (!saveFrontPath.exists()) {
            saveFrontPath.mkdirs();
        }
        //上传到前台文件
        //file.transferTo(new File(frontPath + fileName));//不能在一个方法同时调用两次transferTo方法，因为transferTo是转换的意思，转换完毕file就不存在了
        Files.copy(new File(backendPath + fileName).toPath(),new File(frontPath + fileName).toPath());//将后台的图片复制到前台

        UploadVO uploadVO = new UploadVO();  //
        uploadVO.setMime(file.getContentType());      //类型
        uploadVO.setName(fileName);         //随机文件名字
        uploadVO.setSize(file.getSize());     //大小
        if (type == 1){
            //后台请求
            uploadVO.setSavePath(backendRelativePath + fileName);  //文件地址
        }else {
            //前台请求
            uploadVO.setSavePath(frontRelativePath + fileName);  //文件地址
        }
        return uploadVO;
    }
}
